import hal
import glib
import time

debug = 1

class HandlerClass:
	text = ""
	capital = 0
	shift = 0
	'''
	class with gladevcp callback handlers
	'''
	def __init__(self, halcomp,builder,useropts):
		'''
		Handler classes are instantiated in the following state:
		- the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
		- the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
		- it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.
		
		after all handlers are instantiated in command line and get_handlers() order, callbacks will be
		connected with connect_signals()/signal_autoconnect()
		The builder may be either of libglade or GtkBuilder type depending on the glade file format.
		'''
		
		self.halcomp = halcomp
		self.builder = builder
	
	def on_key_pressed(self,widget,data=None):
		'''
		a callback method
		parameters are:
		the generating object instance, likte a GtkButton instance
		user data passed if any - this is currently unused but
		the convention should be retained just in case
		'''
		self.text = self.text+widget.get_label()
		self.builder.get_object('text').set_label(self.text)
		if self.shift:
			self.shift = 0
			self.capital = 1-self.capital
			self.change_text()
	def on_backspace_pressed(self,widget,data=None):
		self.text=self.text[:-1]
		self.builder.get_object('text').set_label(self.text)
	def on_enter_pressed(self,widget,data=None):
		self.text=self.text+"\n"
		self.builder.get_object('text').set_label(self.text)
	def on_caps_pressed(self,widget,data=None):
		self.capital = 1-self.capital
		self.change_text()
	def on_tab_pressed(self,widget,data=None):
		self.text=self.text+"\t"
		self.builder.get_object('text').set_label(self.text)
	def on_shift_pressed(self,widget,data=None):
		self.shift = 1-self.shift
		self.capital = 1-self.capital;
		self.change_text()
	def on_done_pressed(self,widget,data=None):
		print "Done"
	def change_text(self):
		'''
		'1','2','3','4','5','6','7','8','9','0','-'
		'''
		for i in ['q','w','e','r','t','y','u','i','o','p',
				  'a','s','d','f','g','h','j','k','l',
				  'z','x','c','v','b','n','m']:
			if self.capital:
				self.builder.get_object('c'+i).set_label(i.capitalize())
			else:
				self.builder.get_object('c'+i).set_label(i.lower())
		

def get_handlers(halcomp,builder,useropts):
	'''
	this function is called by gladevcp at import time (when this module is passed with '-u <modname>.py')
	
	return a list of object instances whose methods should be connected as callback handlers
	any method whose name does not begin with an underscore ('_') is a  callback candidate
	
	the 'get_handlers' name is reserved - gladevcp expects it, so do not change
	'''
	return [HandlerClass(halcomp,builder,useropts)]
